#include <iostream>
#include <winsock2.h>

using namespace std;
int main(){
    WORD sockVersion = MAKEWORD(2,2);
    WSADATA wsaData;
    if(WSAStartup(sockVersion,&wsaData)!=0){
        cout << "版本出错"<<endl;
        return 0;
    }


    SOCKET slisten = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(slisten == INVALID_SOCKET){
        cout << "socket error!";
        return 0;
    }

    sockaddr_in sin;
    sin.sin_family = AF_INET;
    sin.sin_port = htons(8888);
    sin.sin_addr.S_un.S_addr = INADDR_ANY;
    if(bind(slisten,(*SOCKADDR)&sin,sizeof(sin)) == SOCKET_ERROR){//(LPSOCKADDR)&sin
        cout << "bind error !" << endl;
    }

    if(listen(slisten,5) == SOCKET_ERROR){
        cout << "listen error" << endl;
        return 0;
    }

    SOCKET sClient;
    sockaddr_in remoteAddr;
    int nAddrlen = sizeof(remoteAddr);
    char revData[255];
    while (true){
        cout << "connecting..."<<endl;
        sClient = accept(slisten,(SOCKADDR  *)& remoteAddr, &nAddrlen);
        if(sClient == INVALID_SOCKET){
            cout << "accept error !";
            continue;
        }
        cout << "accept a connection: " << inet_ntoa(remoteAddr.sin_addr)<< "\r\n";
        int ret =recv(sClient,revData,255,0);
        if (ret > 0){
            revData[ret] = 0x00;
            cout << revData << endl;
        }
        const char* sendData = "hello ,i'm server!";
        send(sClient,sendData, 255, 0);
        closesocket(sClient);
    }
    closesocket(slisten);
    WSACleanup();
    return 0;
}
